from typing import Tuple, Callable

from openpyxl.cell.cell import column_index_from_string

from core.cell_data_handler import CellDataHandler
from core.excel_data import ExcelData


class FilteredValueCellDataHandler(CellDataHandler):

    __slots__ = [
        'data',
        'filter_fn',
        'column',
        'generator'
    ]

    def __init__(self, data: ExcelData, filter_fn: Callable[[Tuple], bool], column: str or int):
        self.data = data
        self.filter_fn = filter_fn
        self.column = column if isinstance(column, int) else column_index_from_string(column)
        self.generator = self.__generate_value()

    def __generate_value(self) -> tuple:
        for t in self.data.data:
            if self.filter_fn(t):
                yield t

    def handle(self, row_data: tuple):
        try:
            data = next(self.generator)
            return data[self.column - 1] if data is not None else ''
        except StopIteration:
            return ''
